<?php 
global $_GPC, $_W;
$cfg = $this->module['config'];
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';

if($operation=="login"){
    $userid=$_GPC["userid"];
    $pwd=$_GPC["pwd"];
    if(!$userid || !$pwd)die(json_encode(array("success"=>false,"msg"=>"用户名或者密码错误")));
    $pwd=md5($_GPC['pwd']);
    $item=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and useracount=:a and password=:b limit 1",array(":a"=>$userid,":b"=>$pwd));
    if(!$item)die(json_encode(array("success"=>false,"msg"=>"用户不存在或者密码错误")));
    if(!$item['status'])die(json_encode(array("success"=>false,"msg"=>"该用户还没有审核，请联系管理员")));
    die(json_encode(array("success"=>true,"islogin"=>$item['id'],"user"=>$item)));
}

$userid=$_GPC["islogin"];
if(!$userid)die(json_encode(array("success"=>false,"msg"=>"请先登陆")));
$user=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$userid));
if(!$user)die(json_encode(array("success"=>false,"msg"=>"请先登陆")));
if(!$user['status'])die(json_encode(array("success"=>false,"msg"=>"该用户还没有审核，请联系管理员")));
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid='{$_W['uniacid']}' and id=:a ",array(":a"=>$user['pcate']));
$shopid=$shop["id"];

if ($operation == 'memberpay') {
    $id = $_GPC['id'];
    $paycode = $_GPC['paycode'];
    $pid = $_GPC['pid'];
    $fee = intval($_GPC['fee']);
    $keyword = trim($_GPC['keyword']);
    if ($cfg['ispaycode'] && $pid && !$paycode) die(json_encode(array('success' => false, 'msg' => "请输入支付验证码")));
    $condition = "  ";
    if ($keyword) {
        $condition .= "  and (realname =:a or cardno =:a or wxcardno=:a or mobile=:a) ";
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id asc limit 1", array(":a" => $keyword));
    } else {
        if (!$id) die(json_encode(array('success' => false, 'msg' => "请输入ID号")));
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ", array(":a" => $id));
    }
    if (!$member) die(json_encode(array('success' => false, 'msg' => "无此会员")));
    $member['cash2'] = $member['cash'];
    if ($member['uid'] || $member['openid']) {
        $uid = $member['uid'];
        if (!$uid) $uid = mc_openid2uid($member['openid']);
        $memberuser = mc_fetch($uid);
        if ($cfg['isgeneralbalance']) {
            $member['cash2'] = $member['cash2'] + intval($memberuser['credit2'] * 100);
            $this->memberCardInform($member["id"]);
        }
    }
    if ($fee > $member['cash2']) die(json_encode(array('success' => false, 'msg' => "余额不足")));

    if (!$pid) {
        //
        $data = array(
            "weid" => $_W['uniacid'],
            "groupid" => $shopid,
            "userid" => $userid,
            "cid" => $member["id"],
            "usetype" => 1,
            "paytype" => -1,
            "startfee" => $member['cash2'],
            "cash" => $fee,
            "gift" => 0,
            "out_trade_no" => TIMESTAMP . mt_rand(100, 999),
            "createtime" => TIMESTAMP,
            "createdate" => date("Y-m-d"),
            "status" => 0,
        );
        if ($cfg['ispaycode']) {
            $data["paycode"] = mt_rand(1000, 9999);
            pdo_insert("j_hmoney_recharge", $data);
            $pid = pdo_insertid();
            $temp = array(
                "first" => array(
                    "value" => "尊敬的顾客",
                    "color" => "#000000"
                ),
                "number" => array(
                    "value" => $data["paycode"],
                    "color" => "#FF0000"
                ),
                "remark" => array(
                    "value" => "该验证码有效期3分钟可使用1次，转发无效",
                    "color" => "#333333"
                )
            );
            $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account') . " WHERE uniacid=:uniacid ", array(':uniacid' => $_W['uniacid']));
            $acc = WeAccount::create($acid);
            $acc->sendTplNotice($member['openid'], $cfg["tempmsg_paycode"], $temp, "", "#FF0000");
            die(json_encode(array('success' => true, 'pid' => $pid, "memberid" => $member['id'], "needpass" => true)));
        } else {
            $data['endfee'] = $member['cash2'] - abs($fee);
            $data["status"] = 1;
            if ($cfg['isgeneralbalance'] && $uid) {
                $postfee = $this->_2money(($fee * -1));
                mc_credit_update($uid, "credit2", $postfee, array("", "收银系统扣费"));
                $this->memberCardInform($member["id"]);
            } else {
                pdo_update("j_hmoney_membercard", array("cash" => $data['endfee']), array("id" => $member["id"]));
            }
            pdo_insert("j_hmoney_recharge", $data);
            $pid = pdo_insertid();
            $result = $this->_memberSoft($pid);
            die(json_encode(array('success' => true, 'pid' => $pid)));
        }
    } else {
        $order = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE groupid=:a and id=:b", array(":a" => $shopid, ":b" => $pid));
        if ($paycode != $order['paycode']) die(json_encode(array('success' => false, 'msg' => "验证码不正确")));
        $data['endfee'] = $member['cash2'] - abs($order['cash']);
        $data["status"] = 1;
        if ($cfg['isgeneralbalance'] && $uid) {
            $postfee = $this->_2money(($order['cash']));
            mc_credit_update($uid, "credit2", (-1) * $postfee, array("", "收银系统扣费"));
            $this->memberCardInform($member["id"]);
        } else {
            pdo_update("j_hmoney_membercard", array("cash" => $data['endfee']), array("id" => $member["id"]));
        }
        pdo_update("j_hmoney_recharge", $data, array("pid" => $pid));
    }
    $result = $this->_memberSoft($pid);
    die(json_encode(array('success' => true, "pid" => $pid, "result" => $result)));
}elseif($operation == "membercredit"){
    $id = $_GPC['id'];
    $fee = intval($_GPC['fee']);
    $keyword = trim($_GPC['keyword']);
    $credit = trim($_GPC['credit']);
    $condition = "  ";
    if (!$fee)die(json_encode(array('success' => false, 'msg' => "金额不能为空")));
    if ($keyword) {
        $condition .= "  and (realname =:a or cardno =:a or wxcardno=:a or mobile=:a) ";
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id asc limit 1", array(":a" => $keyword));
    } else {
        if (!$id) die(json_encode(array('success' => false, 'msg' => "请输入ID号")));
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ", array(":a" => $id));
    }
    if (!$member) die(json_encode(array('success' => false, 'msg' => "无此会员")));
    if (!$member['uid'] && !$member['openid'])die(json_encode(array('success' => false, 'msg' => "该会员未绑定微信会员卡")));
    $uid = $member['uid'];
    if (!$uid) $uid = mc_openid2uid($member['openid']);
    $memberuser = mc_fetch($uid);
    if (!$memberuser)die(json_encode(array('success' => false, 'msg' => "该会员未绑定微信会员卡")));
    $credit = $cfg['credit'];
    $finalcredit=bcmul($credit,$fee,2);
    mc_credit_update($uid,"credit1",$finalcredit,array("","独立会员模块增加".$finalcredit."积分","j_hmoney",$userid,$shopid));
    $memberuser = mc_fetch($uid);
    pdo_update("j_hmoney_membercard",array("gid"=>$memberuser["groupid"]),array("id"=>$member["id"]));
    load()->func('communication');
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $creditAry2 = mc_credit_fetch($uid, array('credit1'));
    $data=array(
        "card_id"=>$cfg['wxmembercard'],
        "code"=>$member['wxcardno'],
        "bonus"=>$creditAry2['credit1'],
    );
    $pageparama=urldecode(json_encode($data));
    $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/updateuser?access_token=".$tokens,$pageparama, $xml);
    $result=@json_decode($resp['content'],true);
    $this->memberCardInform($member["id"]);
    die(json_encode(array('success' => true, "credit" => $finalcredit)));

}elseif ($operation == 'printtrade') {
    $orderid=$_GPC["pid"];
    $print=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_print')." WHERE weid = '{$_W['uniacid']}' and pcate=4 and groupid=:a order by isdefault desc,id desc limit 1",array(":a"=>$shopid));
    $printdoc=$print['wpcontent'];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$orderid));
    if(strlen($orderid)>=10)$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid = '{$_W['uniacid']}' and out_trade_no=:a ",array(":a"=>$orderid));
    $member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$trade['cid']));
    $printdoc=str_replace("{收银员}",$user['realname'],$printdoc);
    $printdoc=str_replace("{店铺}",$shop['companyname'],$printdoc);
    $printdoc=str_replace("{订单号}",$trade['out_trade_no'],$printdoc);
    $printdoc=str_replace("{开始金额}",$this->_2money(($trade['startfee'])),$printdoc);
    $printdoc=str_replace("开始金额","起始余额",$printdoc);
    $printdoc=str_replace("{结束金额}",$this->_2money(($trade['endfee'])),$printdoc);
    $printdoc=str_replace("结束金额","账户余额",$printdoc);
    $printdoc=str_replace("{赠送金额}",$this->_2money(($trade['gift'])),$printdoc);
    $printdoc=str_replace("赠送金额","其他",$printdoc);
    $printdoc=str_replace("{金额}",$this->_2money(($trade['cash'])),$printdoc);
    $printdoc=str_replace("{支付方式}","余额",$printdoc);
    $printdoc=str_replace("{备注}",$trade['remark'],$printdoc);
    $printdoc=str_replace("{日期}",date("m月d日",$trade['createtime']),$printdoc);
    $printdoc=str_replace("{时间}",date("H:i",$trade['createtime']),$printdoc);
    $printdoc=str_replace("{卡号}",$member['cardno'],$printdoc);
    $printdoc=str_replace("{微信卡号}",$member['wxcardno'],$printdoc);
    $printdoc=str_replace("{打印时间}",date("m/d H:i"),$printdoc);
    $printdoc=str_replace("{行为}","消费",$printdoc);
    die(json_encode(array('success'=>true,'content'=>$printdoc)));
}elseif ($operation == 'printcharge') {
    $orderid=$_GPC["pid"];
    $print=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_print')." WHERE weid = '{$_W['uniacid']}' and pcate=4 and groupid=:a order by isdefault desc,id desc limit 1",array(":a"=>$shopid));
    $printdoc=$print['wpcontent'];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$orderid));
    if(strlen($orderid)>=10)$trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid = '{$_W['uniacid']}' and out_trade_no=:a ",array(":a"=>$orderid));
    $member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$trade['cid']));
    $printdoc=str_replace("{收银员}",$user['realname'],$printdoc);
    $printdoc=str_replace("{店铺}",$shop['companyname'],$printdoc);
    $printdoc=str_replace("{订单号}",$trade['out_trade_no'],$printdoc);
    $printdoc=str_replace("{开始金额}",$this->_2money(($trade['startfee'])),$printdoc);
    $printdoc=str_replace("开始金额","起始余额",$printdoc);
    $printdoc=str_replace("{结束金额}",$this->_2money(($trade['endfee'])),$printdoc);
    $printdoc=str_replace("结束金额","账户余额",$printdoc);
    $printdoc=str_replace("{赠送金额}",$this->_2money(($trade['gift'])),$printdoc);
    $printdoc=str_replace("{金额}",$this->_2money(($trade['cash'])),$printdoc);
    if($trade['usetype']==0){
        $printdoc=str_replace("金额","充值金额",$printdoc);
    }else{
        $printdoc=str_replace("金额","退还金额",$printdoc);
    }
    $printdoc=str_replace("{支付方式}",_getPaytpye($trade['paytype']),$printdoc);
    $printdoc=str_replace("{备注}",$trade['remark'],$printdoc);
    $printdoc=str_replace("{日期}",date("m月d日",$trade['createtime']),$printdoc);
    $printdoc=str_replace("{时间}",date("H:i",$trade['createtime']),$printdoc);
    $printdoc=str_replace("{卡号}",$member['cardno'],$printdoc);
    $printdoc=str_replace("{微信卡号}",$member['wxcardno'],$printdoc);
    $printdoc=str_replace("{打印时间}",date("m/d H:i"),$printdoc);
    $printdoc=str_replace("{行为}",$trade['usetype']==0 ? "充值" : "退还",$printdoc);
    die(json_encode(array('success'=>true,'content'=>$printdoc)));
}elseif ($operation == 'output') {
    $starttime=explode(" ",$_GPC['ds']);
    $starttime=strtotime($starttime[0]." 00:00:00");
    $endtime=explode(" ",$_GPC['de']);
    $endtime=strtotime($endtime[0]." 23:59:59");
    $keyword=trim($_GPC['keyword']);
    $sqlkey=array(":a"=>$shopid,":b"=>$starttime,":c"=>$endtime);
    $condition=" and a.groupid =:a ";
    $condition.=" and a.createtime>=:b and a.createtime<=:c";
    if($keyword){
        $condition.=" and ( a.out_trade_no =:d )";
        $sqlkey[":d"]=$keyword;
    }
    $list = pdo_fetchall("SELECT a.*,b.cardno,b.realname FROM ".tablename('j_hmoney_recharge')." a left join ".tablename('j_hmoney_membercard')." b on a.cid=b.id WHERE a.weid = '{$_W['uniacid']}' $condition  order by a.id desc  ",$sqlkey);

    require_once "../framework/library/phpexcel/PHPExcel.php";
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("智慧收银台")
        ->setLastModifiedBy("智慧收银台")
        ->setTitle("数据EXCEL导出")
        ->setSubject("数据EXCEL导出")
        ->setDescription("备份数据")
        ->setKeywords("excel")
        ->setCategory("result file");
    //"单号", "卡号", "方式", "开始", "金额", "结束", "时间", "状态", "打印"
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1',"单号")
        ->setCellValue('B1',"卡号")
        ->setCellValue('C1',"方式")
        ->setCellValue('D1',"开始金额")
        ->setCellValue('E1',"金额")
        ->setCellValue('F1',"赠送金额")
        ->setCellValue('G1',"结束金额")
        ->setCellValue('H1',"时间")
        ->setCellValue('I1',"状态");
    $num=2;
    $statusary=array(0=>"未处理",1=>"完成",2=>"退款",);
    $usetypeary=array(0=>"充值",1=>"消费",2=>"退还",);
    foreach($list as $row){
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.$num, "'".$row['out_trade_no'])
            ->setCellValue('B'.$num, "'".$row['cardno'])
            ->setCellValue('C'.$num, $usetypeary[$row['usetype']])
            ->setCellValue('D'.$num, $this->_2money($row['startfee']))
            ->setCellValue('E'.$num, $this->_2money($row['cash']))
            ->setCellValue('F'.$num, $this->_2money($row['gift']))
            ->setCellValue('G'.$num, $this->_2money($row['endfee']))
            ->setCellValue('H'.$num, date("Y-m-d H:i",$row['createtime']))
            ->setCellValue('I'.$num, $statusary[$row['status']]);
        $num++;
    }
    $objPHPExcel->getActiveSheet()->setTitle('消费记录');
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition:attachment;filename="trade_temp.xls"');
    header('Cache-Control:max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit();

}elseif ($operation == 'gettradelist') {
    $starttime=explode(" ",$_GPC['ds']);
    $starttime=strtotime($starttime[0]." 00:00:00");
    $endtime=explode(" ",$_GPC['de']);
    $endtime=strtotime($endtime[0]." 23:59:59");
    $keyword=trim($_GPC['keyword']);
    $usetype=intval($_GPC['usetype'])>-1 ? $_GPC['usetype'] : "";

    $condition=" and a.groupid = ".$shopid;
    $condition.=" and a.createtime>=  ".$starttime." and a.createtime<=".$endtime;
    if($keyword)$condition.=" and ( a.out_trade_no = '" . $keyword . "' )";
    if($usetype!="")$condition.=" and  a.usetype = '" . $usetype . "' ";
    $list = pdo_fetchall("SELECT a.*,b.cardno,b.realname FROM ".tablename('j_hmoney_recharge')." a left join ".tablename('j_hmoney_membercard')." b on a.cid=b.id WHERE a.weid = '{$_W['uniacid']}' $condition  order by a.id desc  ");

    #$total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' $condition  ");
    die(json_encode(array('success'=>true,'list'=>$list,'a'=>$condition,)));

}elseif ($operation == 'getcreditlist') {
    $date=explode(" ",$_GPC['ds']);
    $starttime=strtotime($date[0]." 00:00:00");
    $endtime=strtotime($date[0]." 23:59:59");
    $condition="uniacid = ".$_W['uniacid']." and credittype='credit1' and module='j_hmoney' and store_id=".$shopid." and createtime>=  ".$starttime." and createtime<=".$endtime;
    $credit = pdo_fetchcolumn("SELECT sum(num) FROM ".tablename('mc_credits_record')." WHERE  $condition   ");
    die(json_encode(array('success'=>true,'credit'=>$credit,'a'=>$starttime."-".$endtime)));

}elseif ($operation == 'refundorder') {
    $ordersn=$_GPC[
    "ordersn"];
    $trade=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_recharge')." WHERE weid = '{$_W['uniacid']}' and out_trade_no=:a ",array(":a"=>$ordersn));
    if(!$trade)die(json_encode(array('success' => false, 'msg' => "订单不存在")));
    if($trade['status']!=1)die(json_encode(array('success' => false, 'msg' => "该订单不能退款/或已经退款")));
    $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a", array(":a" => $trade['cid']));
    $member['cash2'] = $member['cash'];
    if ($member['uid'] || $member['openid']) {
        $uid = $member['uid'];
        if (!$uid) $uid = mc_openid2uid($member['openid']);
        $memberuser = mc_fetch($uid);
        if ($cfg['isgeneralbalance']) {
            $member['cash2'] = $member['cash2'] + intval($memberuser['credit2'] * 100);
            $this->memberCardInform($member["id"]);
        }
    }
    $data = array(
        "weid" => $_W['uniacid'],
        "groupid" => $shopid,
        "userid" => $userid,
        "cid" => $member["id"],
        "usetype" => 2,
        "paytype" => -1,
        "startfee" => $member['cash2'],
        "cash" => $trade['cash'],
        "gift" => 0,
        "endfee" => $member['cash2']+$trade['cash'],
        "out_trade_no" => TIMESTAMP . mt_rand(100, 999),
        "createtime" => TIMESTAMP,
        "createdate" => date("Y-m-d"),
        "status" => 1,
    );
    pdo_insert("j_hmoney_recharge",$data);
    $pid=pdo_insertid();
    pdo_update("j_hmoney_recharge",array("status"=>2),array("id"=>$trade["id"]));
    pdo_update("j_hmoney_membercard",array("cash"=>$member["cash"]+$trade['cash']),array("id"=>$member["id"]));
    $this->memberCardInform($member["id"]);
    $result=$this->_memberSoft($pid);
    die(json_encode(array('success'=>true)));

}elseif ($operation == 'getmemberlist') {
    $condition = "  ";
    if($_GPC['keyword'])$condition.= " and (wxcardno like '%" . $_GPC['keyword'] . "%' or cardno like '%" . $_GPC['keyword'] . "%' mobile like '%" . $_GPC['keyword'] . "% or realname like '%" . $_GPC['keyword'] . "%')";
    $list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by status asc,cardno asc,id desc ");
    if($cfg['isgeneralbalance']){
        if($_GPC['keyword'])$condition= " and (a.wxcardno like '%" . $_GPC['keyword'] . "%' or a.realname like '%" . $_GPC['keyword'] . "%' or a.cardno like '%" . $_GPC['keyword'] . "%' or a.mobile like '%" . $_GPC['keyword'] . "%' )";
        $list = pdo_fetchall("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' $condition order by a.status asc,a.cardno asc,a.id desc ");

    }

    $groupAry=array();
    $groupAry[0]="";
    load()->model('mc');
    foreach(mc_groups() as $row){
        $groupAry[$row['groupid']]=$row['title'];
    }
    if($list){
        for($i=0;$i<count($list);$i++){
            $temp1=$this->_2money((($list[$i]['credit']*100+$list[$i]['credit1']*100)));
            $list[$i]['credit']=$temp1;
            $temp2=$this->_2money((($list[$i]['cash']+$list[$i]['credit2']*100)));
            $list[$i]['cash']=$temp2;
            $list[$i]['level']=$groupAry[$list[$i]['gid']];
        }
    }
    die(json_encode(array('success'=>true,'list'=>$list)));

}elseif ($operation == 'getmember') {
    $groupAry=array();
    load()->model('mc');
    foreach(mc_groups() as $row){
        $groupAry[$row['groupid']]=$row['title'];
    }
    $id=$_GPC['memberid'];
    $membercardno=$_GPC['membercardno'];
    if($id) {
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ", array(":a" => $id));
        if (!$member) die(json_encode(array('success' => false, 'msg' => "请输入ID号")));
        if ($cfg['isgeneralbalance']) {
            $member = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM " . tablename('j_hmoney_membercard') . " a left join " . tablename('mc_members') . " b on a.uid=b.uid WHERE a.id=:a  ", array(":a" => $id));
        }
    }
    if($membercardno){
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and (cardno=:a or wxcardno=:b) ", array(":a" => $membercardno,":b" => $membercardno));
        if (!$member) die(json_encode(array('success' => false, 'msg' => "请输入ID号")));
        if ($cfg['isgeneralbalance']) {
            $member = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM " . tablename('j_hmoney_membercard') . " a left join " . tablename('mc_members') . " b on a.uid=b.uid WHERE (a.cardno=:a or a.wxcardno=:b)  ", array(":a" => $membercardno,":b" => $membercardno));
        }
    }
    if($member){
        $temp1 = $this->_2money( (($member['credit'] * 100 + $member['credit1'] * 100) ));
        $member['credit'] = $temp1;
        $temp2 = $this->_2money( (($member['cash'] + intval($member['credit2'] * 100)) ));
        $member['cash'] = $temp2;
        $member['level'] = $groupAry[$member['gid']];
    }

    $chargestr=" ";
    $chargelist=strlen($shop['chargelist'])>5 ? json_decode($shop['chargelist'],true) : "";
    if($chargelist){
        $chargestr="充值优惠：<br>";
        foreach($chargelist as $index=>$val){
            $chargestr.="充￥<b style='color:#F60'>".$index."</b>送￥<b style='color:#0ac'>".$val."</b> " ;
        }
    }
    die(json_encode(array('success'=>true,'member'=>$member,'memberlevel'=>$groupAry,'chargestr'=>$chargestr)));

}elseif ($operation == 'updatemember') {
    $id = intval($_GPC['memberid']);
    $groupAry = array();
    load()->model('mc');
    foreach (mc_groups() as $row) {
        $groupAry[$row['title']] = $row['groupid'];
    }
    $data = array(
        "weid" => $_W["uniacid"],
        "groupid" => $shopid,
        "cardno" => $_GPC["cardno"],
        "userid" => $userid,
        "gid" => intval($_GPC["level"]),
        "realname" => urldecode($_GPC["realname"]),
        "mobile" => $_GPC["mobile"],
        "wxcardno" => $_GPC["wxcardno"],
        "status" => intval($_GPC["ustatus"]),
    );
    $update = array(
        "cardno" => $data["cardno"],
        "wxcardno" => $data["wxcardno"],
    );
    if ($id) {
        unset($data['userid']);
        unset($data['groupid']);
        unset($data['weid']);
        $isused = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and cardno=:b and id<>:a ", array(":a" => $id, ":b" => $data['cardno'], ":c" => $_W['uniacid']));
        if ($isused) die(json_encode(array('success' => false, 'msg' => "修改实体卡号重复".$id)));
        if ($data["wxcardno"]) {
            $isused = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and wxcardno=:b and id<>:a ", array(":a" => $id, ":c" => $_W['uniacid'], ":b" => $data['wxcardno']));
            if ($isused) die(json_encode(array('success' => false, 'msg' => "微信卡号重复")));
        }
        pdo_update("j_hmoney_membercard", $data, array("id" => $id));
        $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE id=:a ", array(":a" => $id));
        $update['uid'] = $member['uid'];
        $update['openid'] = $member['openid'];
    } else {
        $isused = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and cardno=:b ", array(":b" => $data['cardno'], ":c" => $_W['uniacid']));
        if ($isused) die(json_encode(array('success' => false, 'msg' => "新增实体卡号重复")));
        if ($data["wxcardno"]) {
            $isused = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and wxcardno=:b ", array(":c" => $_W['uniacid'], ":b" => $data['wxcardno']));
            if ($isused) die(json_encode(array('success' => false, 'msg' => "微信卡号重复")));
        }
        pdo_insert("j_hmoney_membercard", $data);
        $id = pdo_insertid();
    }
    if ($update['wxcardno'] && $cfg['wxmembercard'] && (!$update['openid'] || !$update['uid'])) {
        $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account') . " WHERE uniacid=:uniacid ", array(':uniacid' => $_W['uniacid']));
        $acc = WeAccount::create($acid);
        $tokens = $acc->fetch_token();
        $pageparama = json_encode(array("card_id" => $cfg['wxmembercard'], "code" => $update['wxcardno']));
        $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=" . $tokens, $pageparama, $xml);
        $result = @json_decode($resp['content'], true);
        if (!$result['errcode']) {
            $openid = $result['openid'];
            $uid = mc_openid2uid($openid);
            pdo_update("j_hmoney_membercard", array("openid" => $openid, "uid" => $uid), array("id" => $id));
            $this->memberCardInform($id);
        }
    }
    die(json_encode(array('success' => true)));

}elseif($operation == 'membercharge'){
    //充值
    $id=intval($_GPC['memberid']);
    $cash=intval(abs($_GPC['cash'])*100);
    $paytype=intval($_GPC['paytype']);
    $qrcode=trim($_GPC['qrcode']);
    if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入会员卡号")));
    $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a", array(":a" => $id));
    if(!$member)die(json_encode(array('success'=>false,'msg'=>"请输入ID号，error")));
    if($member['status']!=1)die(json_encode(array('success'=>false,'msg'=>"该会员卡状态异常，无法进行处理")));
    if($cash==0)die(json_encode(array('success'=>false,'msg'=>"请输入金额")));

    $finalcasch = $member['cash'];
    if ($member['uid'] || $member['openid']) {
        $uid = $member['uid'];
        if (!$uid) $uid = mc_openid2uid($member['openid']);
        $memberuser = mc_fetch($uid);
        if ($cfg['isgeneralbalance']) {
            $finalcasch =  $finalcasch+intval($memberuser['credit2'] * 100);
            $this->memberCardInform($member["id"]);
        }
    }

    if($paytype==9){
        if($qrcode)$paytype = substr($qrcode, 0, 1) == 1 ? 0 : 1;
    }
    if($paytype==9)die(json_encode(array('success'=>false,'msg'=>"异常")));
    //--检查满送--//
    $gift=0;
    $chargelist=strlen($shop['chargelist'])>5 ? json_decode($shop['chargelist'],true) : "";
    if($chargelist){
        foreach($chargelist as $index=>$val){
            if($cash<intval($index*100))break;
            $gift=intval($val*100);
        }
    }
    //-//
    $data=array(
        "weid"=>$_W['uniacid'],
        "groupid"=>$shopid,
        "userid"=>$userid,
        "cid"=>$id,
        "usetype"=>0,
        "paytype"=>$paytype,
        "startfee"=>$finalcasch,
        "cash"=>$cash,
        "gift"=>intval($gift),
        "out_trade_no"=>TIMESTAMP.mt_rand(100,999),
        "remark"=>$_GPC['remark'],
        "createtime"=>TIMESTAMP,
        "createdate"=>date("Y-m-d"),
        "status"=>0,
    );
    pdo_insert("j_hmoney_recharge",$data);
    $pid=pdo_insertid();

    switch($data['paytype']){
        case 2:
        case 3:
            $data['status']=1;
            break;
        case 0:
            if($cfg['isbank']){
                $bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
                pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
                $result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
                if($result['status'] || $result['result_code']){
                    if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
                        die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
                    }
                    die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
                }
                $data["status"]=1;
            }else{
                if(!$qrcode)die(json_encode(array('success'=>false,'msg'=>"请输入支付码")));
                $payParama=array(
                    "appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
                    "pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
                    "pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
                    "outTradeNo"=>strval($data['out_trade_no']),
                    "pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
                    "sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
                    "sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
                );
                $pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
                $pageparama=array(
                    "appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
                    "mch_id"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
                    "device_info"=>$deviceinfo,
                    "nonce_str"=>getNonceStr(),
                    "body"=>$shop['companyname'],
                    "detail"=>"充值",
                    "attach"=>"-",
                    "out_trade_no"=>$payParama['outTradeNo'],
                    "total_fee"=>$data['cash'],
                    "fee_type"=>"CNY",
                    "spbill_create_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
                    "goods_tag"=>"000001",
                    "auth_code"=>$qrcode,
                );
                if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
                if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
                $sign=MakeSign($pageparama,$pay_signkey);
                $pageparama['sign']=$sign;
                $xml = ToXml($pageparama);
                $response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/micropay", 10);
                $result=FromXml($response);
                if($result['result_code']!='SUCCESS'){
                    if($result['err_code']=='USERPAYING'){
                        die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
                    }
                    die(json_encode(array("success"=>false,"msg"=>$result['err_code_des'])));
                }
                $data["status"]=1;
            }

            break;
        case 1:
            if($cfg['isbank']){
                $bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
                pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
                $result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
                if($result['status'] || $result['result_code']){
                    if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
                        die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
                    }
                    die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
                }
                $data["status"]=1;
            }else{
                $qrcode=$_GPC['qrcode'];
                $payParama=array(
                    "app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
                    "outTradeNo"=>strval($data['out_trade_no']),
                    "appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
                    "alipay_cert"=>$cfg['alipay_cert'],
                    "alipay_key"=>$cfg['alipay_key'],
                    "alipay_store_id"=>$shop['alipay_store_id'] ,
                    "alipid"=>$cfg['alipid'] ,
                );
                $auth_code = trim($qrcode);
                $total_amount = $data['cash'];
                $postfee=$this->_2money(($total_amount));
                require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
                $f2fpay = new F2fpay();
                $response = $f2fpay->barpay($payParama['outTradeNo'],$auth_code,$postfee,$shop['companyname'],$payParama);
                $temp=(array)$response;
                $result=(array)$temp['alipay_trade_pay_response'];
                if($result['code']=="10003"){
                    die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
                }elseif($result['code']=="10000"){
                    $data["status"]=1;
                }else{
                    die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
                }
            }

            break;
    }
    $data['endfee']=$finalcasch+abs($cash)+$data['gift'];
    pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
    if(!$member["uid"]){
        pdo_update("j_hmoney_membercard",array("cash"=>$finalcasch+abs($cash)+$data['gift']),array("id"=>$id));
    }else{
        pdo_update("j_hmoney_membercard",array("cash"=>abs($cash)+$data['gift']),array("id"=>$id));
    }
    $this->memberCardInform($id);
    $this->_memberSoft($pid);
    die(json_encode(array("success"=>true,"out_trade_no"=>$data['out_trade_no'],"pid"=>$pid,"id"=>$id)));

}elseif ($operation == 'waitforpass') {
    $pid=$_GPC['pid'];
    $trade = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
    $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a", array(":a" => $trade['cid']));
    $member['cash2'] = $member['cash'];
    if ($member['uid'] || $member['openid']) {
        $uid = $member['uid'];
        if (!$uid) $uid = mc_openid2uid($member['openid']);
        $memberuser = mc_fetch($uid);
        if ($cfg['isgeneralbalance']) {
            $member['cash2'] = $member['cash2'] + intval($memberuser['credit2'] * 100);
            $this->memberCardInform($member["id"]);
        }
    }
    if($cfg['isbank']){
        $result=Bankpay_checkpay($cfg,$trade['bank_trade_no']);
        if(!$result['status'] && !$result['result_code']){
            if($result['trade_state']=='USERPAYING' || $result['trade_state']=='10003'){
                die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
            }elseif($result['trade_state']=='SUCCESS'){
                $data['endfee']=$member['cash2']+abs($cash)+$trade['gift'];
                $data['status']=1;
                pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
                if($trade["status"]==0){
                    if(!$member["uid"]){
                        pdo_update("j_hmoney_membercard",array("cash"=>$member['cash2']+abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                    }else{
                        pdo_update("j_hmoney_membercard",array("cash"=>abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                        $this->memberCardInform($id);
                    }
                    $this->_memberSoft($pid);
                }
                die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$member['id'])));
            }
            die(json_encode(array("success"=>false,"msg"=>$result['trade_state'])));
        }
        die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));

    }else{
        if($item['paytype']==0){
            $payParama=array(
                "appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
                "pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
                "pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
            );
            $pageparama=array(
                "appid"=>$payParama['appid'],
                "mch_id"=>strval($payParama['pay_mchid']),
                "out_trade_no"=>$trade['out_trade_no'],
                "nonce_str"=>getNonceStr(),
            );
            if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
            if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
            $sign=MakeSign($pageparama,$payParama['pay_signkey']);
            $pageparama['sign']=$sign;
            $xml = ToXml($pageparama);
            $response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/orderquery", 10);
            $result=FromXml($response);
            if($result['result_code']=='SUCCESS'){
                if($result['trade_state']=='USERPAYING'){
                    die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
                }elseif($result['trade_state']=='SUCCESS'){
                    $data['endfee']=$member['cash2']+abs($cash)+$trade['gift'];
                    $data['status']=1;
                    pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
                    if($trade["status"]==0){
                        if(!$member["uid"]){
                            pdo_update("j_hmoney_membercard",array("cash"=>$member['cash2']+abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                        }else{
                            pdo_update("j_hmoney_membercard",array("cash"=>abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                            $this->memberCardInform($id);
                        }
                        $this->_memberSoft($pid);
                    }
                    die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$member['id'])));
                }
            }
            die(json_encode(array("success"=>false,"msg"=>$result['trade_state_desc'].$result['err_code_des'])));

        }else if($item['paytype']==1){
            $payParama=array(
                "app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
                "pemurl"=>$cfg['pemurl'],
                "appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
                "alipay_cert"=>$cfg['alipay_cert'],
                "alipay_key"=>$cfg['alipay_key'],
                "alipay_store_id"=>$shop['alipay_store_id'] ,
                "alipid"=>$cfg['alipid'] ,
            );
            if($payParama['app_id']==$payParama['sub_app_id'])unset($payParama['sub_app_id']);
            require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
            $cfg = $this->module['config'];
            $f2fpay = new F2fpay();
            $response = $f2fpay->query($trade['out_trade_no'],$payParama);
            $results=@json_decode(json_encode($response),true);
            $result=$results['alipay_trade_query_response'];
            if($result['code']==10003){
                die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid,"id"=>$item['id'])));
            }elseif($result['code']==10000){
                if($result['trade_status']=="TRADE_SUCCESS"){
                    $data['endfee']=$member['cash2']+abs($cash)+$trade['gift'];
                    $data['status']=1;
                    pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
                    if($trade["status"]==0){
                        if(!$member["uid"]){
                            pdo_update("j_hmoney_membercard",array("cash"=>$member['cash2']+abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                        }else{
                            pdo_update("j_hmoney_membercard",array("cash"=>abs($cash)+$trade['gift']),array("id"=>$trade['cid']));
                            $this->memberCardInform($id);
                        }
                        $this->_memberSoft($pid);
                    }
                    die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$member['id'])));
                }
            }
            die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
        }
        die(json_encode(array('success'=>true)));
    }
}elseif ($operation == 'reviewmember') {
    $id=intval($_GPC["memberid"]);
    $member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE id=:a ",array(":a"=>$id));

    load()->func('communication');
    $cfg = $this->module['config'];
    $cardid=$cfg["wxmembercard"];
    if(!$cardid)die(json_encode(array("success"=>false,"msg"=>"请先填写会员卡ID并保存后操作")));
    $acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
    $acc = WeAccount::create($acid);
    $tokens=$acc->fetch_token();
    $data2=array(
        "openid"=>$member["openid"],
        "card_id"=>$cardid
    );
    $pageparama=urldecode(json_encode($data2));
    $resp = ihttp_request("https://api.weixin.qq.com/card/user/getcardlist?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die(json_encode(array("success"=>false,"msg"=>$result['errmsg'].$member)));
    $code=$result["card_list"][0]["code"];
    if(!$code)die(json_encode(array("success"=>false,"msg"=>$result['没匹配会员卡'])));
    $tokens=$acc->fetch_token();
    $data=array(
        "membership_number"=>$code,
        "code"=>$code,
        "card_id"=>$cardid
    );
    $pageparama=urldecode(json_encode($data));
    $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/activate?access_token=".$tokens,$pageparama, "");
    $result=@json_decode($resp['content'],true);
    if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die(json_encode(array("success"=>false,"msg"=>$result['errmsg'])));

    $update=array(
        "groupid"=>$member["groupid"] ? $member["groupid"] : $shopid,
        "userid"=>$member["userid"] ? $member["userid"] : $userid,
        "wxcardno"=>$code,
        "status"=>1,
        "createtime"=>TIMESTAMP,
    );
    if(!$member["mobile"]){
        $tokens=$acc->fetch_token();
        $data=array(
            "code"=>$code,
            "card_id"=>$cardid
        );
        $pageparama=urldecode(json_encode($data));
        $resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, "");
        $result=@json_decode($resp['content'],true);
        if($result['errcode'] || !isset($result['errcode']) || $result['errmsg']!="ok")die(json_encode(array("success"=>true,"msg"=>$result['errmsg'])));
        $info=$result['user_info']['common_field_list'];
        $data=array();
        foreach($info as $index=>$row){
            if($row['name']=='USER_FORM_INFO_FLAG_MOBILE'){
                $update['mobile']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_NAME'){
                $update['realname']=$row['value'];
            }elseif($row['name']=='USER_FORM_INFO_FLAG_SEX'){
                if($row["value"]=="男"){
                    $update["sex"]=1;
                }elseif($row["value"]=="女"){
                    $update["sex"]=2;
                }else{
                    $update["sex"]=0;
                }
            }elseif($update['name']=='USER_FORM_INFO_FLAG_BIRTHDAY'){
                $data['birdday']=$row['value'];
            }
        }
    }
    pdo_update("j_hmoney_membercard",$update,array("id"=>$member["id"]));
    die(json_encode(array("success"=>true,'a'=>$update)));

}

